package org.example.exceptionHandler;

import org.example.MyExecption.BusinessException;
import org.example.response.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BusinessException.class)
    public ApiResponse<Object> handleBusinessException(BusinessException e) {
        logger.error("业务异常: {}", e.getMessage());
        return ApiResponse.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(DataAccessException.class)
    public ApiResponse<Object> handleDataAccessException(DataAccessException e) {
        logger.error("数据库访问异常", e);
        return ApiResponse.error(500, "数据库访问异常，请稍后重试");
    }

    @ExceptionHandler(RedisConnectionFailureException.class)
    public ApiResponse<Object> handleRedisConnectionFailureException(RedisConnectionFailureException e) {
        logger.error("Redis连接异常", e);
        return ApiResponse.error(500, "系统缓存异常，请稍后重试");
    }

    @ExceptionHandler(Exception.class)
    public ApiResponse<Object> handleException(Exception e) {
        logger.error("系统异常", e);
        return ApiResponse.error(500, "系统繁忙，请稍后重试");
    }
}